package com.automobile.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.automobile.domain.User;
import com.automobile.service.UserService;

@Controller
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    public static final String CHECK_CODE_KEY = "CHECK_CODE_KEY";


    /*
     * 注册
     */
    @RequestMapping(path = "/register")
    public @ResponseBody Map<String, Object> register(HttpServletRequest request,@RequestBody User user) {

        String checkCode = user.getCheckCode();
        String modelCode = (String) request.getSession().getAttribute(CHECK_CODE_KEY);
        request.removeAttribute(CHECK_CODE_KEY);

        System.out.println(checkCode+":"+modelCode);

        Map<String, Object> msgMap = new HashMap<String, Object>();

        if(modelCode==null||!modelCode.equalsIgnoreCase(checkCode)) {
            System.out.println("验证码错误！");
            msgMap.put("msg", "验证码输入错误，请重新输入");
            msgMap.put("result", 0);
            return msgMap;
        }

        user.setPassword(new SimpleHash("MD5", user.getPassword(), ByteSource.Util.bytes(user.getPhone()), 1024).toString());

        boolean result = userService.registerUser(user);
        System.out.println("result"+result);
        if(!result) {
            msgMap.put("msg", "手机号或邮箱已注册过，如忘记密码请前往修改密码。");
            msgMap.put("result",0);
        }else {
            msgMap.put("result", 1);
        }

        return msgMap;
    }



    /*
     * 激活
     */
    @RequestMapping("/activate")
    public String activate(String activateCode) {

        System.out.println("激活此链接："+activateCode);
        if(activateCode==null) {
            System.out.println("activate is null");
            return "error";
        }
        boolean flag = userService.activate(activateCode);
        if(flag==false) {
            return "error";
        }
        return "redirect:/activate_success.html";
    }

    /*
     * 登录
     */
    @RequestMapping(path = "/login")
    public @ResponseBody Map<String, Object> login(HttpServletRequest request,@RequestBody User user) {

        String checkCode = user.getCheckCode();
        String modelCode = (String) request.getSession().getAttribute(CHECK_CODE_KEY);
        request.removeAttribute(CHECK_CODE_KEY);

        System.out.println(checkCode+":"+modelCode);

        Map<String, Object> msgMap = new HashMap<String, Object>();

        if(modelCode==null||!modelCode.equalsIgnoreCase(checkCode)) {
            System.out.println("验证码错误！");
            msgMap.put("msg", "验证码输入错误，请重新输入");
            msgMap.put("result", 0);
            return msgMap;
        }

        Subject currentUser = SecurityUtils.getSubject();
        if(!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(user.getPhone(),user.getPassword());

            try {
                currentUser.login(token);
            } catch (IncorrectCredentialsException e){
                msgMap.put("msg", "账号密码错误");
                msgMap.put("result", 0);
                return msgMap;
            } catch (AuthenticationException e) {
                msgMap.put("msg", e.getMessage());
                msgMap.put("result", 0);
                return msgMap;
            }

        }


        msgMap.put("result", 1);

        return msgMap;
    }


    /*
     * 获取用户
     */
    @RequestMapping("/findUser")
    public @ResponseBody User findUser(HttpServletRequest request) {
        User user = null;
        Object obj = SecurityUtils.getSubject().getPrincipal();
        if(obj!=null && obj instanceof User){
            user = (User) obj;
        }else{
            user = new User();
        }
        return user;
    }


    //----------------------------------backstage----------------------------------//

    @RequestMapping("/findAll")
    public @ResponseBody List<User> findAll(@RequestParam(value = "page",required = true,defaultValue = "1")Integer page,
                                            @RequestParam(value = "limit",required = true,defaultValue = "10")Integer limit){
        System.out.println(page+":"+limit);
        List<User> users = userService.findAll();
        System.out.println("-------------------------"+users);
        return users;
    }

}
